package com.qingxin.sys.support;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingxin.sms.service.SmsQueryService;
import com.qingxin.sys.smslib.SmsFactory;
import com.qingxin.sys.smslib.SmsInDataThread;
import com.qingxin.sys.smslib.SmsOutDataThread;


/**
 * 用于在系统启动时进行初始化操作和在系统停止时进行资源回收操作
 * @author Administrator
 *
 */
public class QxSystemListener implements ServletContextListener {

	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		BaseThreadManager.getInstance().stopAll();
		try {
			org.quartz.impl.StdScheduler scheduler = (org.quartz.impl.StdScheduler) context.getBean("scheduler");
			if(scheduler != null){
				scheduler.shutdown();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SmsFactory.stopServer();
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		
		StartThread startThread = new StartThread(context);
		startThread.start();
	}

	
	//用于启动服务线程
	//该类作用在于延时启动服务线程且不影响主服务器的启动
	private class StartThread extends Thread {
		private WebApplicationContext context;
		
		protected StartThread(WebApplicationContext context) {
			this.context = context;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(10000);
			} catch (Exception e) {
			}
			//TODO 初始化代码
			SmsOutDataThread smsOutDataThread = SmsOutDataThread.getInstance();
			BaseThreadManager.getInstance().add(smsOutDataThread);
			
			SmsInDataThread smsInDataThread = SmsInDataThread.getInstance();
			BaseThreadManager.getInstance().add(smsInDataThread);
			
			SmsQueryService smsQueryService = context.getBean(SmsQueryService.class);
			SmsFactory.startServer(smsQueryService);
			
		}
	}
}
